package com.colin.juc.threadlocal;

import java.util.concurrent.atomic.AtomicLong;

/**
 * @author zhaodong 2021/5/29 16:1649
 * email: colinzhaodong@gmail.com
 * desc: 给每个线程分配一个唯一id
 */
public class ThreadId {
    static final AtomicLong
            nextId=new AtomicLong(0);
    // 定义 ThreadLocal 变量
    static final ThreadLocal<Long>
            tl=ThreadLocal.withInitial(
            nextId::getAndIncrement);
    // 此方法会为每个线程分配一个唯一的 Id
    static long get(){
        return tl.get();
    }

    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                System.out.println(get());
            }).start();
        }
        tl.remove();
    }
}
